
#include "glutVisualizer.h"

//------------------
//--- GlutThread ---
//------------------

using namespace ttg::threads;

GlutThread *GlutThread::ref = new GlutThread();

void GlutThread::displayFunc()
{
	getRef()->glut_thread.wait();
	for (size_t i = 0; i < getRef()->actions.size(); i++)
	{
		getRef()->actions[i]->invoke();
		SAFE_DELETE(getRef()->actions[i]);
	}
	getRef()->actions.clear();
	getRef()->main_thread.rise();
}

void GlutThread::work()
{
	int argc = 1;
	char *argv[] = { "main.exe" };
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
	glutInitWindowSize(450, 300);
	glutCreateWindow("NBody via ttgLib");
	glutDisplayFunc(&GlutThread::displayFunc);
	glutIdleFunc(&GlutThread::idleFunc);
	glutMainLoop();
	exit(0);
}

void GlutThread::performActions(std::vector<ttg::structures::InvokableObject *> &actions)
{
	this->actions = actions;
	glut_thread.rise();
	main_thread.wait();
}

void GlutThread::init()
{
	if (is_inited)
		throw ttg::Error(ttg::Error::FATAL, "GlutThread", "start",
						 "GlutThread is already started");
	is_inited = true;
	start();
}
